﻿using LcAudit.BPM.Core;
using LcAudit.BPM.Core.Bll;
using LcAudit.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Omu.ValueInjecter;
using System.Data;
using System.Data.OleDb;
using System.IO;


namespace LcAudit.BPM.Admin.bidder.ashx
{
    /// <summary>
    /// bidderhandler 的摘要说明
    /// </summary>
    public class bidderhandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            if (SysVisitor.Instance.IsGuest)
            {
                context.Response.Write(
                    new JsonMessage { Success = false, Data = "-99", Message = "登录已过期，请重新登录" }.ToString()
                    );
                context.Response.End();
            }

            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<LcAudit.BPM.Core.Model.bidderinfo>(context) { CurrentContext = context, Action = context.Request["action"] };
          
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<LcAudit.BPM.Core.Model.bidderinfo>>(json);
                rpm.CurrentContext = context;
            }

            switch (rpm.Action)
            {
                case "add":
                    context.Response.Write(bidderinfoBll.Instance.Add(rpm.Entity));
                    break;
                case "edit":
                    LcAudit.BPM.Core.Model.bidderinfo u = new LcAudit.BPM.Core.Model.bidderinfo();
                    u.InjectFrom(rpm.Entity);
                    u.KeyId = rpm.KeyId;
                    context.Response.Write(bidderinfoBll.Instance.Edit(u));
                    break;

                case "del":
                    var dconfig = PublicMethod.GetInt(rpm.KeyId);
                    string dmsg = bidderinfoBll.Instance.Delete(dconfig);
                    context.Response.Write(dmsg);
                    break;
                case "setbag":
                    string keyid = HttpContext.Current.Request["keyids"];
                    int bagid = PublicMethod.GetInt(HttpContext.Current.Request["bagid"]);
                    int k = bidderinfoBll.Instance.AddBidderToBag(bagid,keyid);
                    context.Response.Write(k);
                    break;
                case "queryall":
                    context.Response.Write(baginfoBll.Instance.GetJsonDataAll(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    break;
                case "up":
                    string bagbh = HttpContext.Current.Request["bagbh"];
                    int id = PublicMethod.GetInt(HttpContext.Current.Request["id"]);
                    HttpPostedFile file = HttpContext.Current.Request.Files[0];
                    string files = LcAudit.Upload.Upload.UploadFile(file, "/upload/" + bagbh + "/" + id + ".doc");
                    context.Response.Write(files);
                    break;
                case "audit":                    
                    int bag_id = PublicMethod.GetInt(HttpContext.Current.Request["bagid"]);                    
                    context.Response.Write(bidderinfoBll.Instance.AuditBag(bag_id));
                    break;
                case "ftxt":
                    int baid = PublicMethod.GetInt(HttpContext.Current.Request["bagid"]);
                    string ft = HttpContext.Current.Request["ftxt"];
                    context.Response.Write(bidderinfoBll.Instance.Ftxt(baid,ft));
                    break;
                case "upexcel":
                    int bagid_excel = PublicMethod.GetInt(HttpContext.Current.Request["bagid"]);
                    int bid_excel = PublicMethod.GetInt(HttpContext.Current.Request["id"]);
                    HttpPostedFile file_excel = HttpContext.Current.Request.Files[0];
                    string files_excel = LcAudit.Upload.Upload.UploadFile(file_excel, "/upload/upexcel/" + bid_excel + ".xls");

                    string orifilename = "";
                    //路径
                    string uploadfilepath = System.Web.HttpContext.Current.Server.MapPath("/");
                    //判断是否有该目录
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
                    if (!uploadfilepath.EndsWith("\\"))
                        orifilename = uploadfilepath + "\\" + files_excel;
                    else
                        orifilename = uploadfilepath + files_excel;

                    string msg = ImportXlsToData(orifilename,bid_excel,bagid_excel);

                    ////如果存在,删除文件
                    //if (File.Exists(orifilename))
                    //{
                    //    File.Delete(orifilename);
                    //}

                    context.Response.Write(file_excel);
                    break;
                default: //字典列表, or 设备列表                    
                    string devJson = bidderinfoBll.Instance.GetList();
                    context.Response.Write(devJson);
                    break;
            }
        }

        private string ImportXlsToData(string fileName,int bid,int bagid)
        {
            try
            {
                if (fileName == string.Empty)
                {
                    throw new ArgumentNullException("Excel文件上传失败！");
                }
                string oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileName + "; Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
                OleDbConnection oleDBConn = null;
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {
                    m_tableName.TableName = "template$";
                }
                string sqlMaster;
                sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                // oleDBConn.Close();
                oleDBConn.Dispose();

                return AddDatasetToSQL(ds, 7,bid,bagid);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private string AddDatasetToSQL(DataSet pds, int Cols,int bid,int bagid)
        {
            string msg = "";

            LcAudit.BPM.Core.Bll.materialprice sm = new LcAudit.BPM.Core.Bll.materialprice();

            int ic, ir;
            ic = pds.Tables[0].Columns.Count;
            if (pds.Tables[0].Columns.Count < Cols)
            {
                throw new Exception("导入Excel格式错误！Excel只有" + ic.ToString() + "列");
            }

            ir = pds.Tables[0].Rows.Count;
            if (pds != null && pds.Tables[0].Rows.Count > 0)
            {
                LcAudit.BPM.Core.Model.materialpriceinfo s = new Core.Model.materialpriceinfo();
                for (int i = 0; i < pds.Tables[0].Rows.Count; i++)
                {
                    #region 循环导入
                    DataRow r = pds.Tables[0].Rows[i];

                    s.mpname = r["材料名称"].ToString().Trim();
                    //if (!string.IsNullOrEmpty(r["合同交货时间"].ToString().Trim()))
                    //{
                    //    try
                    //    {
                    //        s.realSupplyDate = DateTime.Parse(r["合同交货时间"].ToString().Trim());
                    //    }
                    //    catch (Exception)
                    //    {

                    //    }
                    //}

                    s.mpxh = r["规格、型号"].ToString().Trim();
                    s.mpunit = r["单位"].ToString().Trim();
                    s.mpadd = r["产地、品牌"].ToString().Trim();
                    if (!string.IsNullOrEmpty(r["数量"].ToString().Trim()))
                    {
                        try
                        {
                            s.mpnum = decimal.Parse(r["数量"].ToString().Trim());
                        }
                        catch (Exception)
                        {
                            s.mpnum = 0;
                        }
                    }
                    if (!string.IsNullOrEmpty(r["单价（元）"].ToString().Trim()))
                    {
                        try
                        {
                            s.mprice = decimal.Parse(r["单价（元）"].ToString().Trim());
                        }
                        catch (Exception)
                        {
                            s.mprice = 0;
                        }
                    }
                    s.bid = bid;
                    s.bagid = bagid;

                    #endregion

                    if (sm.Insert(s) > 0)
                    {
                        //insertCount += 1;
                    }

                }

                //msg = "一共导入" + insertCount + "条数据。\\n";
                //if (proidNullCount != 0)
                //{
                //    msg += "有" + proidNullCount + "条数据没有填写项目编号无法导入！\\n";
                //}
                //if (equipmentManageNullCount != 0)
                //{
                //    msg += "有" + equipmentManageNullCount + "条数据没有填写设备管理单位无法导入！\\n";
                //}
                //if (equipmentManageNullNameCount != 0)
                //{
                //    msg += "有" + equipmentManageNullNameCount + "条数据在设备管理单位记录表中不存在无法导入！\\n";
                //}

            }
            else
            {
                throw new Exception("导入数据为空！");
            }
            return msg;
        } 

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}